package com.wenwen.social.common.exception;

import com.wenwen.social.controller.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@ControllerAdvice
@Slf4j
public class ExceptionHandlers extends ResponseEntityExceptionHandler {

	@ExceptionHandler(value = GlobalException.class)
	public ResponseEntity<Object> GlobalExceptionHandler(GlobalException ex){
		log.info("不符合操作的异常：{}",ex.getMessage());
		return ResponseEntity.status(HttpStatus.BAD_REQUEST).body( new ResultVO().fail(ex.getMessage()));
	}
	@ExceptionHandler(value = IllegalArgumentException.class)
	public ResponseEntity<Object> IllegalArgumentExceptionHandler(GlobalException ex){
		log.info("参数异常：{}",ex.getMessage());
		return ResponseEntity.status(HttpStatus.BAD_REQUEST).body( new ResultVO().fail(ex.getMessage()));
	}

	@ExceptionHandler(value = ServiceException.class)

	public ResponseEntity<Object> ServiceExceptionHandler(ServiceException ex){
		log.info("ServiceException:{}:{}",ex.code,ex.msg);
		return ResponseEntity.status(HttpStatus.BAD_REQUEST).body( new ResultVO().fail(ex.code,ex.msg));
	}
	//@ExceptionHandler(value = BindException.class)
	@Override
	public ResponseEntity<Object> handleBindException(BindException ex, HttpHeaders headers, HttpStatus status, WebRequest request){
		Map<String, String> messages = new HashMap<>();
		BindingResult result = ex.getBindingResult();
		if (result.hasErrors()) {
			List<ObjectError> errors = result.getAllErrors();
			for (ObjectError error : errors) {
				FieldError fieldError = (FieldError) error;
				messages.put(fieldError.getField(), fieldError.getDefaultMessage());
			}
			log.error("{}",messages.toString(),ex);
		}
		return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ResultVO.fail(HttpStatus.BAD_REQUEST.value(),messages.toString()));

	}
}
